package threadcoreknowledge.createthread.stopthread;

/**
 * 最佳实践2：
 * 在catch语句中调用Thread.currentThread.interrupt来恢复设置中断，
 * 以便在后续的执行中依然能够检查到发生的中断，
 * 回到刚才的RightWayStopThreadInProd让它跳出来
 */
public class RightWayStopThreadInProd2 implements Runnable {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RightWayStopThreadInProd2());
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }

    @Override
    public void run() {
        while(true){
            System.out.println("go");
            //如果有异常抛出则执行
            if(Thread.currentThread().isInterrupted()){
                System.out.println("Interrupted,程序运行结束");
                break;
            }
            reInterrupt();
        }
    }

    private void reInterrupt(){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            e.printStackTrace();

        }
    }
}
